<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;

use think\Config;
use think\Validate;//验证
use fast\Random;
use fast\Http;

use app\api\controller\Xiaohe;
use app\api\controller\Yuyue;
use app\api\controller\Pay;


/**
 * 扫码⚽︎
 */
class Scancode extends Xiaohe
{

    protected $noNeedLogin = ['index','door_open','error2','test_door_open','add_door_open'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
       
        parent::_initialize();
    }


    /**
     * 开门（暂时没用了
     * 
     * @param int $id 场地id
     * @param int $min 预玩多少分钟
     * @return void
     */
    public function open($id=null,$min=60)
    {
        $space = $this->verify_space_id($id);
        $uid = $this->auth->id;

        $Yuyue = new Yuyue();
        $Pay   = new   Pay();

        //判断 是否有后付费的进场订单 并支付
        $end_pay_order = $Yuyue->get_end_pay_order_and_pay($space['id'],$uid);
        if($end_pay_order){
            $pay_data = $Pay->pay_end_pay_order($end_pay_order);
            $this->success('支付订单',$pay_data,8);
        }

        //查询是否有预定 或者 包场的
        


        //没有预定包场或包场的 生成订单




        //判断是否绑定手机号
        $this->user_is_bang_tel($uid);


        



        // 直接生成预付订单
        
        $data = $Yuyue->create_end_pay_order($space['id'],$this->auth->id,$min);
        


        //开门
        $Device = new Device();

        // halt($end_pay_order);
        
        if(isset($data['door']) && $data['door']=='in'){
            //开进门
            $Device->door_open($space['device_id'],'in');
        }elseif(isset($data['door']) && $data['door']=='out'){
            //开出门
            $Device->door_open($space['device_id'],'out');
        }
        
        $this->error('未知错误');
        
    }

    // /**
    //  * 模拟开门调试接口
    //  *
    //  * @param string $str 扫码后的字符串
    //  * @return void
    //  */
    // public function test_door_open(,$str=null)
    // {
    //     $data = json_decode($str,TRUE);
    //     if($data){
    //         $this->door_open($data['devicenumber'],$data['vgdecoderesult']);
    //     }else{
    //         $this->error('非扫码结果');
    //     }
    // }


    /**
     * 开门
     *
     * @param string $devicenumber 设备id号
     * @param string $vgdecoderesult 解码内容
     * @param string $bug 调试模式=false
     * @return void
     */
    public function door_open($devicenumber = null,$vgdecoderesult=null,$bug = false)
    {
        
          
       
        $Yuyue = new Yuyue();
        
        $Pay   = new   Pay();
        
       
      
        //获取设备提交的参数
        //  如果提交为空
        if(empty($devicenumber) && empty($vgdecoderesult)){
            $input = $this->request->Getinput();
            if(empty($input)){
                $this->error('no params','没有任何参数提交');
            }
            $p = explode('&&', $input);

            // $params = new array();
            foreach ($p as $key => $val) {
                $param = explode('=', $val);
                // print_r($param);
                $params[$param[0]] = $param[1];
            } 
            //    print_r($params);
            //如果没有提交参数
            if(isset($params['devicenumber']) && isset($params['vgdecoderesult'])){
                $devicenumber = $params['devicenumber'];
                $vgdecoderesult = $params['vgdecoderesult'];
            }else{
                //写入到日志
                file_put_contents('device_log'.date('Y-m-d'),json_encode($input));
                $this->error2($uid,'没有该参数');
            }
            if(!empty($vgdecoderesult)){
                file_put_contents(date('Y-m-d').'.txt', date('Y-m-d_H_i_s ').$devicenumber.'____'.$vgdecoderesult.PHP_EOL, FILE_APPEND);

            }
            

        }

        
        //验证解码内容是否正确
        if($bug){
            $data = json_decode($this->deStr(html_entity_decode($vgdecoderesult)),true);
        }else{
            $data = json_decode($this->deStr($vgdecoderesult),true);
        }
        
       
        
    
        if(!$data){
            $this->error2(1,'二维码错误',$data);
        }
        if(isset($data['time'])){
            if($data['time']<= (time()-6000)){
                $this->error2($data['uid'],'二维码过期');
            }
        }else{
            $this->error('数据不正确',$data);
        }

        
        //验证设备号是否存在
        $device = $this->verify_device_id($devicenumber);
      
        // if($bug){halt($device);}
        $uid = $data['uid'];
        switch ($data['status']) {
            case 'in':
                if($device['status']=='2')$this->error2($uid,'此二维码是进场二维码');
                break;
            case 'out':
                if($device['status']=='1')$this->error2($uid,'此二维码是出场二维码');
                break;
            default:
                //
                break;
        }
        
        // halt($data);
        switch ($data['type']) {
            case '1':
                //个人 


                    //进
                    if($data['status']=='in'){  



                        $space_id = $device['space_id'];
                        //验证场馆
                        $space = $this->verify_space_id($space_id);
                        if($space['play_status']=='2'){
                            //陪玩状态:1=正常营业,2=停止营业
                            $this->error2($uid,'此场馆已停止营业');
                        }elseif($space['apply_status']!='1'){
                            //申请状态:1=通过,2=申请中,3=已拒绝
                            $this->error2($uid,'此场馆未通过营业');
                        }
                        
                        //验证是否在营业时间
                        $this->verify_space_work_time($space_id,time());

                        //验证当前时间是否有包场
                        $this->verify_space_now_time_baochang($space_id,time());

                        //验证多少分钟后是否有包场
                        $this->verify_space_now_time_baochang($space_id,time()+60*60);
                       

                        // 创建订单
                        $order_data = $Yuyue->create_end_pay_order($devicenumber,$data['uid']);
                        // $yuyue_order = Db::name('yuyue')->where('order',$vgdecoderesult)->find();
                        if(!$order_data)    {$this->error2($uid,'创建错误');}

                        //开门
                        $this->add_door_open($devicenumber,null,'个人到场',$uid);
                        
                        
                    }elseif($data['status']=='out'){
                    //出门  结算 计时金额
                        $yuyue_order = $this->get_baochang_all_data($data['order']);//Db::name('yuyue')->where('order',$data['order'])->find();
                        
                        if(!$yuyue_order)   {  $this->error2($uid,'没有支付订单信息,请支付');}
                     
                        if($yuyue_order['pay_status']=='2'){
                    
                            if($yuyue_order['paly_status']=='2'){
                                
                                $this->add_door_open($devicenumber,$data['order'],'个人到场出',$uid);
                              
                                //修改出门时间
                                $this->update_daochang_out_data($data['order']);
                            }else{

                                //运动状态:1=待进入,2=进行中,3=时间已到,4=完成,5=超时未进
                                switch ($yuyue_order['paly_status']) {
                                    case '1':
                                        $this->error2($uid,'未入场');
                                        break;
                                    case '4':
                                        $this->error2($uid,'该订单已结束');
                                        break;
                                    default:
                                        $this->error2($uid,'其他未知信息，请联系管理');
                                        break;
                                }

                                
                            }
                            
                        }else{
                            $this->error2($uid,'该订单非已支付状态');
                        }
                    }
                    
                break;
            case '2':
                //包场
               
                $yuyue_order = $this->get_baochang_all_data($data['order']);//Db::name('yuyue')->where('order',$data['order'])->find();
                if(!$yuyue_order)   {  $this->error2($uid,'没有该包场订单信息');}

                //进
                if($data['status']=='in'){
                    
                    //如果支付了就
                    if($yuyue_order['pay_status']!='2') { $this->error2($uid,'该包场订单非支付状态');}

                    if($yuyue_order['s_time']>time())   { $this->error2($uid,'该包场订单时间未到'); }

                    if($yuyue_order['paly_status']=='2'){//运动状态:1=待进入,2=进行中,3=时间已到,4=完成,5=超时未进
                        $this->error2($uid,'已场内');
                    }


                    //修改订单信息
                    $this->update_baochang_in_data($data['order']);
                    $this->add_door_open($devicenumber,$data['order'],'包场进',$uid);

                    
                }elseif($data['status']=='out'){

                    if($yuyue_order['paly_status']!='2'){//运动状态:1=待进入,2=进行中,3=时间已到,4=完成,5=超时未进
                        $this->error2($uid,'未在场内');
                    }
                    //判断是否超时
                    if($yuyue_order['e_time']<time()){
                        //超时扣除违约金
                        $this->add_door_open($devicenumber,$data['order'],'包场出，超时',$uid);

                    }else{
                        //未超时 返还押金
                        $this->add_door_open($devicenumber,$data['order'],'包场出',$uid);
                    }
                        

                    //修改包场订单
                    $this->update_baochang_out_data($data['order']);
                    

                }
                
                break;
            
            default:
                //这里可以搞个一次性二维码没有订单的那种开门
                $this->error2($uid,'错误二维码');
                break;
        }

       


    }


    //出错
    public function error2($uid,$msg,$data=null)
    {
        $data['time'] = time();
        $data['uid'] = $uid;
        $data['msg'] = $msg;
        $data['status'] = '1';
        Db::name('msg')->insert($data);
        //用于调试到那个那个用户
        $this->error($msg,$data);
    }

    /**
     * 开门
     *
     * @param string $devicenumber 设备编号
     * @param string $order 订单号可空
     * @param string $ps 备注
     * @return void
     */
    protected function add_door_open($devicenumber,$order=null,$ps=null,$uid=null)
    {
        $Device = new Device();
        $Device ->add_device_log($devicenumber,$order,$ps,$uid);//添加日志 开门或关门
        echo 'code=0000';
    }


}